<template>
  <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :title="props.title"
      :width="props.width"
  >
    <template #header>
      <div class="flex-row" style="font-size: 18px">
        <el-icon style="margin-right: 8px">
          <Position/>
        </el-icon>
        {{ title }}
      </div>
    </template>

    <base-form
        v-if="fields"
        ref="formRef"
        v-model="formData"
        :fields="fields"
    >
      <template v-for="field in fields" :key="field.prop" v-slot:[`${field.prop}`]="slotProps">
        <slot :name="`${field.prop}`" :row="formData" v-bind="slotProps"></slot>
      </template>
    </base-form>

    <slot :data="formData" name="default"></slot>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="info" @click="close">
          <el-icon><Close/></el-icon>
          <span>关闭</span>
        </el-button>
        <el-button :loading="loading" type="primary" @click="handleSubmit">
          <el-icon><Select/></el-icon>
          <span>确定</span>
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {nextTick, ref} from 'vue'
import BaseForm from './BaseForm.vue'
import {Position, Select} from "@element-plus/icons-vue"

const props = defineProps({
  title: {
    type: String,
    default: '表单'
  },
  width: {
    type: String,
    default: '600px'
  },
  fields: {
    type: Array,
    required: false
  }
})

const emit = defineEmits(['submit'])

// 内部状态
const dialogVisible = ref(false)
const formRef = ref(null)
const formData = ref({})
const loading = ref(false)

// 处理表单提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true
    emit('submit', formData.value)
  } catch (error) {
    console.log('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 打开弹窗
const open = async (data = {}) => {
  dialogVisible.value = true
  formData.value = data
  await nextTick(() => {
    formRef.value?.initForm(data)
  })
}

// 关闭弹窗
const close = () => {
  resetForm()
  dialogVisible.value = false
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetForm()
}

// 暴露方法
defineExpose({
  open,
  close
})
</script>